package dm.api;

import java.util.Iterator;
import dm.api.filter.ViewFilter;
import dm.bsi.Container;
import dm.bsi.Deployment;
import dm.bsi.Image;
import dm.bsi.Node;
import dm.bsi.Service;
import indi.zjh.dp.access.Api;
import indi.zjh.dp.access.ApiContext;
import indi.zjh.dp.db.Configuration;
import indi.zjh.dp.db.Session;
import indi.zjh.dp.orm.Query;
import indi.zjh.dp.orm.Result;

public class GetContainersApi extends Api {

	@Override
	public void process(ApiContext ctx) throws Exception {
		// TODO Auto-generated method stub
		Session session = Configuration.getSessionFactory().createSession();
		try
		{
			ViewFilter viewFilter = new ViewFilter(ctx);
			viewFilter.preprocess();
			
			String deploymentName = ctx.getRequestParamValue("deploy");
			
			Result<Container> containerResult = null;
			Query<Container> containerQuery = new Query<Container>(session);
			
			// 如果输入部署名称, 则查找该部署关联的容器
			if(deploymentName != null && !deploymentName.isEmpty())
			{
				Query<Deployment> deploymentQuery = new Query<Deployment>(session);
				Result<Deployment> deploymentResult = deploymentQuery.find(Deployment.class, "`name` = '"+deploymentName+"'").result();
				if(deploymentResult.count() == 0)
				{
					throw new Exception("部署名称["+deploymentName+"]不存在");
				}
				Deployment deployment = deploymentResult.iterator().next();
				containerResult = containerQuery.find(Container.class, "`state` <> "+Container.NOT_RUNNING).association(Container.class, Service.class).association(Service.class, Deployment.class, "`_id` = "+deployment.getId()).result();
			}
			// 查找全部容器
			else
			{
				containerResult = containerQuery.find(Container.class, "`state` <> "+Container.NOT_RUNNING).result();
			}
			
			viewFilter.writeResponse("Name\tNode\tStatus\tPort\tImage");
			
			Iterator<Container> iter = containerResult.iterator();
			while(iter.hasNext())
			{
				Container container = iter.next();
				String nodeName = "未知";
				if(container.getNode().size() > 0)
				{
					long nodeid = container.getNode().iterator().next();
					Node node = (Node)session.getById(Node.class, nodeid);
					nodeName = node.getName();
				}
				String imageName = "未知";
				if(container.getImage().size() > 0)
				{
					long imageid = container.getImage().iterator().next();
					Image image = (Image)session.getById(Image.class, imageid);
					imageName = image.getName();
				}
				viewFilter.writeResponse(container.getOid()+"\t"+nodeName+"\t"+(container.getState() == Container.RUNNING ? "Y" : "N")+"\t"+container.getDockerPort()+"\t"+imageName);
			}

			ctx.writeResponse("OK");
		}
		catch(Exception e)
		{
			ctx.writeResponse("FAIL:"+e.getMessage());
			session.rollback();
			e.printStackTrace();
		}
		finally {
			session.close();
		}
	}

}
